<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, UserAuth, UserConfig, Payment, Message, Machine, MachineLog, MoneyLog, Price, Config, Wallet, Withdraw, Hall};
use app\facade\Mns;
use app\facade\Eth;
use think\Validate;
use think\Facade\Env;
use think\facade\Log;


use think\Db;


class User extends Base
{
    public function userconfig()
    {
        $result = [];
        $userconfig = (new UserConfig())->where('level', $this->request->user['level'])->find();
        $result['halltotal'] = (new Hall())->where(['status' => [0, 1]])->sum('surplus') ?? 0;
        $result['handfee'] = floor($userconfig['handfee'] * 100 ?? 0) / 10000;
        $result['reput'] = $this->request->user['reput'];
        $result['widthhandfee'] = floor($userconfig['widthhandfee'] * 100 ?? 0) / 10000;
        $this->result($result, 0, '获取成功');
    }
    //注册账号
    public function register()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'code' => 'require',
            'password' => 'require',
            'trade' => 'require',
            'invite' => 'require'
        ], [
            'mobile.require' => '手机号不能为空',
            'code.require' => '短信验证码不能为空',
            'password.require' => '登录密码必须填写',
            'trade.require' => '交易密码必须填写',
            'invite.require' => '邀请码必须填写'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //查找账号是否已存在
        $haveuser = (new Users())->where(['mobile' => $data['mobile']])->find();
        if (!empty($haveuser)) {
            $this->result([], 1, '账号已注册');
        }
        //验证手机验证码
        $mns = (new Mns())->checkCode($data['code'], $data['mobile']);
        if (!$mns) {
            $this->result([], 1, '验证码错误');
        }
        $pid = 0;
        $ppid = 0;
        $pppid = 0;
        $pstree = '';
        if (!empty($data['invite'])) {
            $puser = (new Users())->where('code', $data['invite'])->find();
            if (empty($puser)) {
                $this->result([], 1, '推荐人不存在');
            }
            $pid = $puser['id'] ?? 0;
            $ppid = $puser['pid'] ?? 0;
            $pppid = $puser['ppid'] ?? 0;
            if (empty($puser['pstree'])) {
                $pstree = $puser['id'];
            } else {
                $pstree = $puser['id'] . ',' . $puser['pstree'];
            }
        }
        $code = recode(new Users());
        $token = md5(md5($code . time()));
        $reput = (new Config())->where('key_value', 'reput')->value('value') ?? 5;
        $save = [
            'mobile' =>  $data['mobile'],
            'password' =>  md5(md5($data['password'])),
            'trade' =>  md5(md5($data['trade'])),
            'reput' => $reput,
            'code' => $code,
            'pstree' => $pstree,
            'pid' => $pid,
            'ppid' => $ppid,
            'pppid' => $pppid,
            'token' => $token
        ];
        Db::startTrans();
        try {
            (new Users())->insert($save);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result($e->getMessage(), 1, '注册失败，请重试');
        }
        $register = (new Config())->where('key_value', 'android')->value('value') ?? '';
        $this->result(['token' => $token, 'register' => $register], 0, '注册成功');
    }

    //账号登录
    public function Login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'type' => 'require|in:1,2',
            'mobile' => 'require',
            'code' => 'require',
        ], [
            'type.require' => '登录类型不能为空',
            'type.in' => '登录类型错误',
            'mobile.require' => '账号不能为空',
            'code.require' => '验证码必须填写',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Users())->where('mobile', $data['mobile'])->find();
        if (empty($user)) {
            $this->result([], 1, '账号不存在');
        }
        if ($data['type'] == 1) {
            if (!Redis::get($data['code'])) {
                $this->result([], 1, '验证码错误或已失效');
            }
            if (md5(md5($data['password'])) != $user['password']) {
                $this->result([], 1, '密码错误');
            }
        } else {
            $mns = (new Mns())->checkCode($data['code'], $data['mobile']);
            if (!$mns) {
                $this->result([], 1, '验证码错误');
            }
        }
        $token = md5(md5($user['code'] . time()));
        //更新token
        $res = (new Users())->where('id', $user['id'])->update(['token' => $token]);
        if ($res) {
            Redis::setex($token, 86400 * 5, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '登录失败，请重试');
    }

    public function Forget()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'code' => 'require',
            'password' => 'require',
            'type' => 'require|in:1,2'
        ], [
            'mobile.require' => '账号不能为空',
            'code.require' => '验证码必须填写',
            'password.require' => '更改密码必须填写',
            'type.require' => '修改类型必须填写',
            'type.in' => '更改密码类型不正确',

        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //查找账号是否已存在
        $user = (new Users())->where(['mobile' => $data['mobile']])->find();
        if (empty($user)) {
            $this->result([], 1, '用户不存在');
        }
        //验证手机验证码
        $mns = (new Mns())->checkCode($data['code'], $data['mobile']);
        if (!$mns) {
            $this->result([], 1, '验证码错误');
        }
        $password = md5(md5($data['password']));
        if ($data['type'] == 1) {
            if ($password == $user['password']) {
                $this->result([], 0, '修改密码与原密码相同');
            }
            $res = (new Users())->where('id', $user['id'])->update(['password' => $password]);
        } else {
            if ($password == $user['trade']) {
                $this->result([], 0, '修改密码与原密码相同');
            }
            $res = (new Users())->where('id', $user['id'])->update(['trade' => $password]);
        }

        if ($res) {
            $this->result([], 0, '修改成功');
        }
        $this->result([], 1, '修改失败，请重试');
    }

    public function userauth()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'cards' => 'require',
                'obverse' => 'require',
                'rbverse' => 'require',
            ], [
                'name.require' => '姓名不能为空',
                'cards.require' => '身份证号码不能为空',
                'obverse.require' => '身份证正面不能为空',
                'rbverse.require' => '身份证反面不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //查找账号是否已存在
            $userauth = (new UserAuth())->where('user_id', $this->request->user_id)->find();
            if (!empty($userauth) && $userauth['status'] == 2) {
                $this->result([], 1, '您已认证通过，无需重复认证');
            }
            $data['user_id'] = $this->request->user_id;
            $data['status'] = 1;
            if (empty($userauth)) {
                $res = (new UserAuth())->allowfield(true)->save($data);
            } else {
                $res = (new UserAuth())->allowfield(true)->save($data, ['user_id' => $data['user_id']]);
            }
            if ($res) {
                $this->result([], 0, '提交成功，请等待审核');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            $data = [
                'user_id' => $this->request->user_id,
                'name' => '',
                'cards' => '',
                'obverse' => '',
                'rbverse' => '',
                'status' => 0,
                'info' => ''
            ];
            $result = (new UserAuth())->where('user_id', $this->request->user_id)->field('created,updated', true)->find() ?? $data;
            $this->result($result, 0, '获取成功');
        }
    }


    public function payment()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2',
                'cards' => 'require',
            ], [
                'type.require' => '类型不能为空',
                'type.in' => '类型值不正确',
                'cards.require' => '账号不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            switch ($data['type']) {
                case '1':
                    if (empty($data['images'])) {
                        $this->result([], 1, '付款码不能为空');
                    }
                    if (!empty($data['name'])) {
                        unset($data['name']);
                    }
                    break;
                case '2':
                    if (empty($data['name'])) {
                        $this->result([], 1, '开户行不能为空');
                    }
                    if (!empty($data['images'])) {
                        unset($data['images']);
                    }
                    break;
            }
            //查找账号是否已存在
            $payment = (new Payment())->where(['user_id' => $this->request->user_id, 'type' => $data['type']])->find();
            $data['user_id'] = $this->request->user_id;
            if (empty($payment)) {
                $res = (new Payment())->allowfield(true)->save($data);
            } else {
                $res = (new Payment())->allowfield(true)->save($data, ['id' => $payment['id']]);
            }
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            $type = $this->request->get('type/d', 0);
            $data = [
                'type' => 0,
                'name' => '',
                'cards' => '',
                'images' => ''
            ];
            $result = (new Payment())->field('type,name,cards,images')->where(['user_id' => $this->request->user_id, 'type' => $type])->find() ?? $data;
            $this->result($result, 0, '获取成功');
        }
    }

    public function infoEdit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $nickname = !empty($data['nickname']) ? $data['nickname'] : $this->request->user['nickname'];
            $logo = !empty($data['logo']) ? $data['logo'] : $this->request->user['logo'];
            $res = (new Users())->where('id', $this->request->user_id)->update(['nickname' => $nickname, 'logo' => $logo]);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        }
    }

    public function message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require'
            ], [
                'title.require' => '反馈问题不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['images'])) {
                $images = json_decode($data['images'], true);
                if (empty($images) || count($images) <= 0) {
                    Log::write($data, 'test');

                    $this->result([], 1, '图片格式错误');
                }
            }
            $data['user_id'] = $this->request->user_id;
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            $result = (new Message())->field('title,reply,created,replytime,images')->order('id desc')->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($result as $results) {
                $results['images'] = json_decode($results['images'], true);
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function info()
    {
        $user = $this->request->user;
        $usdt = (new Config())->where('key_value', 'usdt')->value('value') ?? 6.45;
        $pprice = (new Config())->where('key_value', 'exchange')->value('value') ?? 0; //$price代币兑换1算力
        $price = (new Price())->where('date', date('Y-m-d'))->value('price') ?? 0;
        $user['share'] = 'https://' . Env::get('app.api_url') . '/register?code=' . $user['code'];
        unset($user['password']);
        unset($user['created']);
        unset($user['updated']);
        unset($user['trade']);
        unset($user['token']);
        unset($user['pid']);
        unset($user['ppid']);
        unset($user['pppid']);
        $user['id'] = $user['code'];
        $user['tmoney_cny'] = floor($user['tmoney'] * $price * $usdt * 1000000) / 1000000;
        $user['pmoney_cny'] = floor($user['pmoney'] * $pprice * $price * $usdt * 1000000) / 1000000;
        $user['umoney_cny'] = floor($user['umoney'] * $usdt * 1000000) / 1000000;
        $user['price'] = $price;
        $user['ex1'] = $pprice;
        $this->result($user, 0, '获取成功');
    }

    public function machine()
    {
        $result = (new Machine())->field('status,level,created', true)->where('status', 1)->select();
        $this->result($result, 0, '获取成功');
    }

    public function buymachine()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'type' => 'require|in:2,3',
            'id' => 'require',
            'trade' => 'require',
        ], [
            'type.require' => '类型不能为空',
            'type.in' => '类型值不正确',
            'id.require' => '矿机ID不能为空',
            'trade.require' => '交易密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $machine = (new Machine())->where(['status' => 1, 'id' => $data['id']])->find();
        if (empty($machine)) {
            $this->result([], 1, '产品不存在或已下架');
        }
        $user = $this->request->user;
        $machinelogcount = (new MachineLog())->where(['user_id' => $user['id'], 'machineid' => $data['id'], 'type' => 1])->count();
        if ($machinelogcount >= $machine['pur']) {
            $this->result([], 1, '您购买的该类型矿机已达到购买上限');
        }
        if ($user['trade'] != md5(md5($data['trade']))) {
            $this->result([], 1, '交易密码错误');
        }
        switch ($data['type']) {
            case '2':
                $price = (new Config())->where('key_value', 'exchange')->value('value') ?? 0;
                if (empty($price)) {
                    $this->result([], 1, '资产与算力比例出错');
                }
                $money = floor($machine['price'] / $price * 100) / 100;
                if ($user['pmoney'] < $money) {
                    $this->result([], 1, '算力数目不足');
                }
                break;
            case '3':
                $money = $machine['price'];
                if ($user['tmoney'] < $money) {
                    $this->result([], 1, '资产不足');
                }
                break;
            default:
                $this->result([], 1, '类型错误，请重试');
                break;
        }
        //查询redis库存
        $machines_sku = Redis::get('machine_' . $data['id']);
        if ($machines_sku == false) {
            Redis::set('machine_' . $data['id'], $machine['sku'] ?? 0);
            $machines_sku = Redis::get('machine_' . $data['id']);
        }
        if ($machines_sku <= 0) {
            $this->result([], 1, '库存不足');
        }
        Db::startTrans();
        try {
            $id = (new MachineLog())->insertGetId([
                'user_id' => $user['id'],
                'level' => $machine['level'],
                'machineid' => $machine['id'],
                'money' => $machine['price'],
                'power' => $machine['power'],
                'dividends' => $machine['dividends'],
                'ddividends' => $machine['day_dividends'],
                'day' => $machine['day'],
                'lday' => $machine['day'],
                'status' => 1,
                'type' => 1,
                'days' => date('Y-m-d H:i:s')
            ]);
            (new Users())->MoneyEdit($user, $data['type'], 2, -$money, '购买矿机消耗', $id, 0, 0);
            if ($data['type'] == 2) {
                $user['pmoney'] = $user['pmoney'] - $money;
            }
            (new Users())->MoneyEdit($user, 2, 11, $machine['power'], '购买矿机赠送', $id, 0, 0);
            (new Machine())->where(['id' => $data['id']])->setDec('sku', 1);
            Redis::set('machine_' . $data['id'], $machine['sku'] - 1);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result($e->getMessage(), 1, '操作失败，请重试');
        }
        $this->result([], 0, '操作成功');
    }

    public function mymachine()
    {
        $status = $this->request->get('status/d', 0);
        $result = (new MachineLog())->order('id desc')->where('user_id', $this->request->user_id);
        if (!empty($type)) {
            $result = $result->where('status', $status);
        }
        $result = $result->field('id,machineid,money,dividends,ddividends,day,lday,status')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $machine = (new Machine())->where('id', $results['machineid'])->find();
            $results['name'] = $machine['name'] ?? '';
            $results['cover'] = $machine['cover'] ?? '';
        }
        $this->result($result, 0, '获取成功');
    }

    public function mypool()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (!empty($id)) {
                $result = (new MachineLog())->where('income', '>', 0)->where('id', $id)->field('id,machineid,income')->where('user_id', $this->request->user_id)->select();
            } else {
                $result = (new MachineLog())->where('income', '>', 0)->field('id,machineid,income')->where('user_id', $this->request->user_id)->select();
            }
            if (count($result) <= 0) {
                $this->result([], 1, '无可领取收益');
            }
            $income = 0;
            $ids = [];
            foreach ($result as $results) {
                $ids[] = $results['id'];
                $income += $results['income'];
            }
            if ($income > 0) {
                $user = $this->request->user;
                Db::startTrans();
                try {
                    (new MachineLog())->where(['id' => $ids])->update(['income' => 0]);
                    (new Users())->MoneyEdit($user, 3, 4, $income, '领取收益', 0, 0, 0);
                    if ($user['pid'] > 0) {
                        $puser = (new Users())->where('id', $user['pid'])->find();
                        $rate = (new UserConfig())->where('level', $puser['level'])->value('pincome') ?? 0;
                        $pincome = floor($income * $rate * 100) / 10000;
                        (new Users())->MoneyEdit($puser, 3, 13, $pincome, '一代收益', 0, 0, $user['id']);
                    }
                    if ($user['ppid'] > 0) {
                        $ppuser = (new Users())->where('id', $user['ppid'])->find();
                        $prate = (new UserConfig())->where('level', $ppuser['level'])->value('ppincome') ?? 0;
                        $ppincome = floor($income * $prate * 100) / 10000;
                        (new Users())->MoneyEdit($ppuser, 3, 14, $ppincome, '二代收益', 0, 0, $user['id']);
                    }
                    if ($user['ppid'] > 0) {
                        $pppuser = (new Users())->where('id', $user['pppid'])->find();
                        $pprate = (new UserConfig())->where('level', $pppuser['level'])->value('pppincome') ?? 0;
                        $pppincome = floor($income * $pprate * 100) / 10000;
                        (new Users())->MoneyEdit($pppuser, 3, 15, $pppincome, '三代收益', 0, 0, $user['id']);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result($e->getMessage(), 1, '领取失败，请重试');
                }
                $this->result([], 0, '操作成功');
            } else {
                $this->result([], 0, '无可领取收益');
            }
        } else {
            $data = [
                'total' => 0,
                'list' => []
            ];
            $result = (new MachineLog())->where('income', '>', 0)->field('id,machineid,income')->where('user_id', $this->request->user_id)->select();
            foreach ($result as $results) {
                $results['name'] = (new Machine())->where('id', $results['machineid'])->value('name') ?? '';
                // $data['total'] += $results['income'] ?? 0;
            }
            $total = (new MoneyLog())->where(['user_id' => $this->request->user_id, 'type' => 4])->where('created', '>=', date('Y-m-d'))->sum('money') ?? 0;
            $data['total'] += $total;
            $data['list'] = $result;
            $this->result($data, 0, '获取成功');
        }
    }

    public function exchange()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'number' => 'require|float',
            'trade' => 'require',
            'type' => 'require|in:1,2,3',
            'totype' => 'require|in:1,2,3',
        ], [
            'number.require' => '数量不能为空',
            'number.float' => '数量必须是数字',
            'trade.require' => '交易密码不能为空',
            'type.require' => '兑换币种不能为空',
            'type.in' => '兑换币种数值不正确',
            'totype.require' => '被兑换币种不能为空',
            'totype.in' => '被兑换币种数值不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if ($data['type'] == $data['totype']) {
            $this->result([], 1, '兑换与被兑换资产不能一致');
        }
        if ($data['type'] == 3 && $data['totype'] != 1) {
            $this->result([], 1, '当前兑换通道未开放');
        }
        $data['number'] = floor($data['number'] * 100) / 100;
        $user = $this->request->user;
        if ($user['trade'] != md5(md5($data['trade']))) {
            $this->result([], 1, '交易密码错误');
        }

        $number = 0;
        switch ($data['type']) {
            case 1:
                //u兑换算力
                if ($data['totype'] == 2) {
                    $price = (new Config())->where('key_value', 'exchange')->value('value') ?? 0;
                    if (empty($price)) {
                        $this->result([], 1, '兑换比例出错');
                    }
                    $price1 = (new Price())->where('date', date('Y-m-d'))->value('price') ?? 0;
                    if (empty($price)) {
                        $this->result([], 1, '平台价格未设置');
                    }
                    $number = floor($data['number'] * $price / $price1 * 100) / 100;

                    if ($number < 0.01) {
                        $this->result([], 1, '兑换算力不能低于0.01');
                    }
                }
                //u兑换代币
                if ($data['totype'] == 3) {
                    $price = (new Price())->where('date', date('Y-m-d'))->value('price') ?? 0;
                    if (empty($price)) {
                        $this->result([], 1, '平台价格未设置');
                    }
                    $number = floor($data['number'] / $price * 100) / 100;
                }
                break;
            case 3:
                //u兑换代币
                if ($data['totype'] == 1) {
                    $price = (new Price())->where('date', date('Y-m-d'))->value('price') ?? 0;
                    if (empty($price)) {
                        $this->result([], 1, '平台价格未设置');
                    }
                    $number = floor($data['number'] * $price * 100) / 100;
                }
                if ($data['totype'] == 2) {
                    $price = (new Config())->where('key_value', 'exchange')->value('value') ?? 0;
                    if (empty($price)) {
                        $this->result([], 1, '兑换比例出错');
                    }
                    $number = floor($data['number'] * $price * 100) / 100;
                }
                break;
            default:
                $this->result([], 1, '该交易对兑换通道暂不支持');
                break;
        }
        Db::startTrans();
        try {
            (new Users())->MoneyEdit($user, $data['type'], 2, -$data['number'], $price . '比例兑换消耗', 0, 0, 0);
            (new Users())->MoneyEdit($user, $data['totype'], 2, $number, $price . '比例兑换获得', 0, 0, 0);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result($e->getMessage(), 1, '兑换失败，请重试');
        }
        $this->result([], 0, '兑换成功');
    }

    public function getaddress()
    {
        $user_id = $this->request->user_id;
        $type = 1;
        //查询类型是否存在
        $wallet = (new Wallet())->field('address')->where(['type' => $type, 'user_id' => $user_id])->find();
        if (empty($wallet)) {
            try {
                $data = (new ETH())->wallet();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result($e->getMessage(), 1, '地址获取出错，请重试');
            }
            $private = rand(1000, 9999) . 'E' . $data['private'];
            if (strlen($private) < 68) {
                $this->result([], 1, '地址获取出错，请重试');
            }
            $res = (new Wallet())->insert([
                'user_id' => $this->request->user_id,
                'type' => $type,
                'address' => $data['address'],
                'private' => $private,
            ]);
            if (!$res) {
                $this->result([], 1, '地址获取出错，请重试');
            }
            $address = $data['address'];
        } else {
            $address = $wallet['address'];
        }
        $this->result($address, 0, '获取成功');
    }

    public function getrecharge()
    {
        $user_id = $this->request->user_id;
        $user = $this->request->user;

        $rdx_recharge = 'recharge' . $user_id;
        if (!Redis::get($rdx_recharge)) {
            Redis::setex($rdx_recharge, 5, $user_id);
            //进行充值查询
            $ethkeys = '9D8KX5N8TR55M2F86IR4EEKCKVZH21FY95';
            $wallets = (new Wallet())->where(['user_id' => $user_id, 'type' => 1])->find();
            if (empty($wallets)) {
                $this->result([], 1, '查询失败');
            }
            $contact = '0xdac17f958d2ee523a2206206994597c13d831ec7';
            $coinlength = 6;
            $rmoney = 0;
            $url = 'http://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=' . $contact . '&address=' . $wallets['address'] . '&apikey=' . $ethkeys;
            $resulturl = api_curl($url, []);
            $result = json_decode($resulturl, true);
            if (!empty($result) && $result['status'] == 1 && $result['result'] > 0) {
                $havmoney = floor($result['result'] * 10000 / pow(10, $coinlength)) / 10000;
                $rmoney =  $havmoney - $wallets['money'];
                $rmoney = $rmoney * 1000 / 1000;
                //充值金额数目
                if ($rmoney >= 1) {
                    Db::startTrans();
                    try {
                        (new Wallet())->where(['id' => $wallets['id']])->update(['money' => $havmoney]);
                        (new Users())->MoneyEdit($user, 1, 1, $rmoney, 'USDT充值入账', 0, 0, 0);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                }
            }
        }
        $this->result([], 0, '查询完成');
    }

    public function moneylog()
    {
        $atype = $this->request->get('atype/d', 0);
        $result = (new MoneyLog())->order('id desc')->field('info,money,created')->where(['user_id' => $this->request->user_id, 'atype' => $atype])->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($result, 0, '获取成功');
    }

    public function myteam()
    {
        $data = [];
        $result = (new Users())->field('mobile,level,id,created,pid,ppid,pppid,auth')
            ->where(['pid|ppid|pppid' => $this->request->user_id])->select();
        $cuser = 0;
        foreach ($result as $results) {
            $results['team_name'] = '';
            $results['team_income'] = (new MoneyLog())->where(['user_id' => $this->request->user_id, 'type' => [13, 14, 15], 'comeuser_id' => $results['id']])->sum('money');
            if ($results['pid'] == $this->request->user_id) {
                $results['team_name'] = '一级';
            }
            if ($results['ppid'] == $this->request->user_id) {
                $results['team_name'] = '二级';
            }
            if ($results['pppid'] == $this->request->user_id) {
                $results['team_name'] = '三级';
            }
            if ($results['auth'] == 2) {
                $cuser += 1;
            }
            unset($results['pid']);
            unset($results['ppid']);
            unset($results['pppid']);
            unset($results['auth']);
        }
        $data['total'] = (new MoneyLog())->where(['user_id' => $this->request->user_id, 'type' => [13, 14, 15]])->sum('money');
        $data['result'] = $result;
        $data['cuser'] = $cuser;
        $data['nuser'] = count($result);
        $this->result($data, 0, '获取成功');
    }

    public function withdrawal()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'cointype' => 'require',
                'coinnum' => 'require|gt:0|float',
                'address' => 'require',
                'trade' => 'require'
            ], [
                'cointype.require' => '币种类型不能为空',
                'coinnum.require' => '币种数量不能为空',
                'coinnum.gt' => '币种数量必须大于0',
                'coinnum.float' => '币种数量必须是数字',
                'address.require' => '提币地址不能为空',
                'trade.require' => '交易密码不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['coinnum'] = floor($data['coinnum'] * 100) / 100;
            $user = $this->request->user;
            if ($user['auth'] != 2) {
                $this->result([], 1, '请先进行实名认证');
            }
            if ($data['cointype'] == 1 && !(preg_match('/^(0x)?[0-9a-fA-F]{40}$/', $data['address']))) {
                $this->result([], 1, '请输入正确的提币地址');
            }
            if ($user['level'] < 1) {
                $this->result([], 1, 'V1以下不能提现');
            }
            if ($user['trade'] != md5(md5($data['trade']))) {
                $this->result([], 1, '交易密码错误');
            }
            //手续费比例
            $handfee = (new UserConfig())->where('level', $user['level'])->value('widthhandfee') ?? 0; //匹配价格幅度范围
            $handfee = floor($handfee * 100) / 10000;
            $fee = 0;
            switch ($data['cointype']) {
                case 1:
                    $withdrawconfig = (new Config())->where('key_value', 'withdrawconfig')->value('value');
                    $withdrawconfig = json_decode($withdrawconfig, true) ?? [];
                    $usdtmin = $withdrawconfig['usdtmin'] ?? 0;
                    $usdtmax = $withdrawconfig['usdtmax'] ?? 0;
                    if ($data['coinnum'] < $usdtmin) {
                        $this->result([], 1, '提取数量不能低于' . $usdtmin . '个');
                    }
                    if ($data['coinnum'] > $usdtmax) {
                        $this->result([], 1, '提取数量不能多于' . $usdtmax . '个');
                    }
                    $fee = $data['coinnum'] * $handfee;
                    if ($user['umoney'] < $data['coinnum']) {
                        $this->result([], 1, '可提现数目不足');
                    }
                    break;
                default:
                    $this->result([], 1, '当前币种提现通道暂未开放');
                    break;
            }
            Db::startTrans();
            try {
                $id = (new Withdraw())->insertGetId([
                    'user_id' => $user['id'],
                    'cointype' => $data['cointype'],
                    'coinnum' => $data['coinnum'],
                    'handfee' => $fee,
                    'address' => $data['address']
                ]);
                if ($data['cointype'] == 1) {
                    (new Users())->MoneyEdit($user, 1, 8, -$data['coinnum'], '提现申请', $id, $fee, 0);
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                dump($e->getMessage());
                $this->result([], 1, '提现申请失败，请稍后重试');
            }
            $this->result([], 0, '提现申请成功');
        } else {
            $data = $this->request->get();
            $validate = new Validate([
                'cointype' => 'require'
            ], [
                'cointype.require' => '币种类型不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            $handfee = (new UserConfig())->where('level', $user['level'])->value('widthhandfee') ?? 0; //匹配价格幅度范围
            $handfee = floor($handfee * 100) / 10000;
            $result = [
                'min' => 0,
                'max' => 0,
                'handfee' => 0
            ];
            switch ($data['cointype']) {
                case 1:
                    $withdrawconfig = (new Config())->where('key_value', 'withdrawconfig')->value('value');
                    $withdrawconfig = json_decode($withdrawconfig, true) ?? [];
                    $usdtmin = $withdrawconfig['usdtmin'] ?? 0;
                    $usdtmax = $withdrawconfig['usdtmax'] ?? 0;
                    $result = [
                        'min' => $usdtmin,
                        'max' => $usdtmax,
                        'handfee' => $handfee
                    ];
                    $this->result($result, 0, '获取成功');
                    break;
                default:
                    $this->result([], 1, '当前币种提现通道暂未开放');
                    break;
            }
        }
    }

    public function withdrawallog()
    {
        $result = (new Withdraw())->where('user_id', $this->request->user_id)
            ->order('id desc')->field('cointype,coinnum,address,status,created,handfee')->order('id desc')
            ->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['coin_name'] = config()['config']['withdrawtype'][$results['cointype']] ?? "";
            $results['status_text'] = config()['config']['withdrawstatus'][$results['status']] ?? "";
        }
        $this->result($result, 0, '获取成功');
    }
}
